import datetime

from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import viewsets
from rest_framework.pagination import PageNumberPagination
from rest_framework.permissions import BasePermission
from rest_framework.response import Response
from rest_framework.views import APIView

from user.models import User, UseRecord
from .ser import *


class PageNum(PageNumberPagination):
    page_size_query_param = 'page_size'


class PcViewSet(viewsets.ModelViewSet):
    queryset = Pc.objects.all()
    serializer_class = PcSerializer  # PcReadSerializer

    def get_serializer_class(self):
        if self.action in ['list', 'retrieve']:
            return PcReadSerializer
        else:
            return PcSerializer

    # permission_classes = (AllowAny,)

    # 指定排序字段, 不设置, 排序功能不起效
    # ordering_fields = ('attention', 'learner', 'create_time')

    # 指定过滤字段, 不设置, 过滤功能不起效
    # filter_fields = ('title', 'desc', 'status', 'course_type', 'course_tag')

    # 自定义分页器 覆盖全局配置
    # pagination_class = PageNum


class UpAPIView(APIView):
    def post(self, request):
        # 上机
        # 1. 用户名, 2.密码 3. 电脑编号
        pass
        username = request.data.get('username')
        password = request.data.get('password')
        pc_num = request.data.get('pc_num')

        # 2. 校验参数
        if all([username, password, pc_num]):
            pass
        else:
            return Response({'code': '999', 'msg': '参数不足'})

        # 3. 获取user, 获取pc
        try:
            user = User.objects.get(username=username, password=password)
        except Exception as e:
            return Response({'code': '999', 'msg': '用户名密码不正确'})
        try:
            pc = Pc.objects.get(number=pc_num)
        except Exception as e:
            return Response({'code': '999', 'msg': '电脑编号不正确'})
        # 4. user是否上机
        if user.is_online:
            return Response({'code': '999', 'msg': '用户已上机'})
        # 5. pc是否上机
        if pc.is_online:
            return Response({'code': '999', 'msg': '电脑已经使用'})

        # 6. 判断余额能补能上一个小时(普通用户, vip)
        if user.is_vip:
            min_fee = pc.area.fee * 0.8
        else:
            min_fee = pc.area.fee
        if user.balance >= min_fee:
            pass
        else:
            return Response({'code': '999', 'msg': '余额不足'})

        # 7. 上机完成,
        # user上机状态,
        user.is_online = True
        user.save()
        # 电脑的上机状态,
        pc.is_online = True
        pc.save()
        # 消费记录
        ur = UseRecord.objects.create(user=user, pc=pc)
        return Response({'code': '0', 'msg': '上机成功', 'data': {
            'ur_id': ur.id,
            'start_time': ur.start_time.strftime("%Y-%m-%d, %H:%M:%S"),
            'fee': ur.fee,
            'balance': user.balance
        }})

    def put(self, request):
        # 计费接口, 前端每秒请求, 更新费用
        pass
        ur_id = request.data.get('ur_id')
        try:
            ur = UseRecord.objects.get(id=ur_id)
        except Exception as e:
            return Response({'code': '999', 'msg': '记录不存在'})

        user = ur.user
        pc = ur.pc

        if user.is_vip:
            fee = pc.area.fee * 0.8
        else:
            fee = pc.area.fee

        if user.balance >= fee:
            ur.fee += fee
            ur.save()
            user.balance -= fee
            user.save()
            return Response({'code': '0', 'msg': '扣费成功', 'data': {
                'ur_id': ur.id,
                'start_time': ur.start_time.strftime("%Y-%m-%d, %H:%M:%S"),
                'fee': ur.fee,
                'balance': user.balance
            }})
        else:
            ur.fee += user.balance
            ur.stop_time = datetime.datetime.now()
            ur.save()
            user.balance = 0
            user.is_online = False
            user.save()
            pc.is_online = False
            pc.save()
            return Response({'code': '2', 'msg': '下机了'})

    def delete(self, requst):
        ur_id = requst.GET.get('ur_id')
        try:
            ur = UseRecord.objects.get(id=ur_id)
        except Exception as e:
            return Response({'code':'999','msg':'id不正确'})

        if ur.stop_time:
            return Response({'code':'0','msg':'已下机'})

        # 下机流程
        user = ur.user
        pc = ur.pc

        user.is_online = False
        user.save()
        pc.is_online = False
        pc.save()
        ur.stop_time = datetime.datetime.now()
        ur.save()
        return Response({'code':'0','msg':'下机成功'})